package mock.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mock.ApplicationContextProvider;
import mock.DataProvider;
import mock.entity.UploadForm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author vladimirs 04.09.2013   17:40
 */
@Controller
@RequestMapping(value = "/FileUploadForm.htm")
public class UploadFormController implements HandlerExceptionResolver {

    protected final Log logger = LogFactory.getLog(getClass());


    @RequestMapping(method = RequestMethod.GET)
    public String showForm(ModelMap model) {
        logger.info("showForm");
        UploadForm form = new UploadForm();
        model.addAttribute("FORM", form);
        return "/FileUploadForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processForm(@ModelAttribute(value = "FORM") UploadForm form, BindingResult result) {
        ApplicationContext context = ApplicationContextProvider.getApplicationContext();
        DataProvider dp = (DataProvider) context.getBean("dataProvider");
        dp.appendData(form.getFile().getFileItem().get());

        return "redirect:index.jsp";
    }


    @Override
    public ModelAndView resolveException(HttpServletRequest arg0,
                                         HttpServletResponse arg1, Object arg2, Exception exception) {
        Map<Object, Object> model = new HashMap<Object, Object>();
        if (exception instanceof MaxUploadSizeExceededException) {
            model.put("errors", "File size should be less then " + ((MaxUploadSizeExceededException) exception).getMaxUploadSize() + " byte.");
        } else {
            model.put("errors", "Unexpected error: " + exception.getMessage());
        }
        model.put("FORM", new UploadForm());
        return new ModelAndView("/FileUploadForm", (Map) model);

    }
}